<template>
  <div>
    <el-dialog
      v-model="userStore.showDialog"
      width="900px"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :lock-scroll="true"
      class="anime-login-dialog"
    >
      <div class="dialog-panel">
        <!-- 二次元背景 -->
        <div class="bg anime-bg">
          <div class="sakura-container">
            <div v-for="n in 12" :key="n" :class="`sakura sakura-${n}`"></div>
          </div>
          <div class="floating-elements">
            <div
              class="floating-element heart"
              style="top: 10%; left: 5%"
            ></div>
            <div
              class="floating-element star"
              style="top: 20%; right: 10%"
            ></div>
            <div
              class="floating-element cloud"
              style="bottom: 15%; left: 15%"
            ></div>
          </div>
          <div class="kawaii-mask"></div>
        </div>

        <el-form
          class="login-register"
          ref="formDataRef"
          :model="form"
          :rules="rules"
          @submit.prevent="doSubmit"
        >
          <div class="tab-panel">
            <div :class="[opType === 0 ? '' : 'active']" @click="showPanel(1)">
              登录
            </div>
            <el-divider direction="vertical" />
            <div :class="[opType === 1 ? '' : 'active']" @click="showPanel(0)">
              注册
            </div>
          </div>

          <!--input输入-->
          <el-form-item prop="email">
            <el-input
              size="large"
              clearable
              placeholder="请输入邮箱"
              v-model="form.email"
              maxLength="150"
              :prefix-icon="Message"
            ></el-input>
          </el-form-item>
          <!--登录密码-->
          <el-form-item prop="password" v-if="opType === 1">
            <el-input
              show-password
              size="large"
              placeholder="请输入密码"
              v-model="form.password"
              :prefix-icon="Lock"
            ></el-input>
          </el-form-item>

          <div v-if="opType === 0">
            <el-form-item prop="nickname" v-if="opType === 0">
              <el-input
                size="large"
                clearable
                placeholder="请输入昵称"
                v-model="form.nickname"
                maxLength="20"
                :prefix-icon="User"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                show-password
                type="password"
                size="large"
                placeholder="请输入密码"
                v-model="form.password"
                :prefix-icon="Lock"
              ></el-input>
            </el-form-item>
            <el-form-item prop="checkPassword">
              <el-input
                show-password
                type="password"
                size="large"
                placeholder="请再次输入密码"
                v-model="form.checkPassword"
                :prefix-icon="Lock"
              ></el-input>
            </el-form-item>

            <el-form-item prop="code">
              <div class="check-code-panel">
                <el-input
                  size="large"
                  placeholder="请输入验证码"
                  v-model="form.code"
                  @keyup.enter="doSubmit"
                  class="check-code-input"
                  :prefix-icon="Eleme"
                ></el-input>
                <el-button
                  type="primary"
                  class="check-code-btn"
                  @click="sendEmailCode"
                >
                  获取验证码
                </el-button>
              </div>
            </el-form-item>
          </div>

          <el-form-item class="bottom-btn">
            <el-button
              type="primary"
              size="large"
              class="login-btn anime-button"
              @click="doSubmit"
            >
              <span v-if="opType === 0">注册</span>
              <span v-if="opType === 1">登录</span>
            </el-button>
          </el-form-item>

          <!-- 添加底部协议 -->
          <div class="agreement">
            登录/注册即表示您同意
            <span class="link">《用户协议》</span>
            和
            <span class="link">《隐私政策》</span>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Eleme, Lock, Message, User } from '@element-plus/icons-vue'
import useUserStore from '@/store/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'
import { sendCode, userRegister } from '@/api/front/user/userController'
import sendCodeParams = API.sendCodeParams

const userStore = useUserStore()

// 当对话框关闭时，通知父组件更新状态
const handleClose = (done: any) => {
  ElMessageBox.confirm('确定要关闭吗？')
    .then(() => {
      done()
      resetForm()
    })
    .catch(() => {})
}

// 0:注册 1:登录
const opType = ref(1)
const formDataRef = ref()

const form = reactive({
  nickname: '',
  email: '',
  password: '',
  checkPassword: '',
  code: '',
})
const resetForm = () => {
  Object.assign(form, {
    nickname: '',
    email: '',
    password: '',
    checkPassword: '',
    code: '',
  })
}
const showPanel = (type: any) => {
  opType.value = type
  resetForm()
}
//向手机发送验证码
const sendEmailCode = async () => {
  if (!form.email) {
    ElMessage.error('请输入邮箱')
    return
  }
  if (!/^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$/.test(form.email)) {
    ElMessage.error('请输入正确的邮箱')
    return
  }
  const params: sendCodeParams = {
    email: form.email,
    // 如果还有其他字段，也在这里添加
  }
  const result = await sendCode(params)
  if (result.data.code === '0') {
    ElMessage.success('验证码发送成功')
  } else {
    ElMessage.error(result.data.message)
  }
}

const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    {
      min: 2,
      max: 16,
      message: '昵称长度应为 4 到 16 位',
      trigger: 'blur',
    },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      pattern: /^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$/,
      message: '邮箱格式不正确',
      trigger: 'blur',
    },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      min: 8,
      max: 20,
      message: '密码长度应为 8 到 20 位',
      trigger: 'blur',
    },
  ],
  checkPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== form.password) {
          callback(new Error('两次输入的密码不一致'))
        } else if (!value || value.length < 8 || value.length > 20) {
          callback(new Error('密码长度应为 8 到 20 位'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      len: 6,
      message: '验证码应为 6 位',
      trigger: 'blur',
    },
  ],
}
const doSubmit = async () => {
  try {
    const valid = await formDataRef.value.validate()
    if (!valid) {
      ElMessage.error('请按格式填写完整信息')
      return
    }
    let response
    if (opType.value === 1) {
      response = await userStore.userLogin(form)

      if (response === 'ok') {
        ElMessage.success('登录成功')
        resetForm()
        userStore.showDialog = false
      }
    } else {
      response = await userRegister(form)
      if (response.data.code === '0') {
        ElMessage.success('注册成功，请在登录页面完成登录')
        opType.value = 1
        resetForm()
      } else {
        ElMessage.error('注册失败')
      }
    }
  } catch (error: any) {}
}

// 稿件上传
</script>

<style scoped lang="scss">
.anime-login-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
    background: transparent;
    box-shadow: 0 5px 25px rgba(255, 105, 180, 0.3);
  }
}

.dialog-panel {
  position: relative;
  display: flex;
  background: transparent;
  border-radius: 12px;
  overflow: hidden;
}

.bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;

  &.anime-bg {
    background-image: url('/src/assets/anime/anime-bg.png');
    background-size: cover;
    background-position: center;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: linear-gradient(
        135deg,
        rgba(255, 183, 197, 0.3),
        rgba(201, 160, 220, 0.3)
      );
      z-index: 1;
      animation: gradientShift 10s ease infinite alternate;
    }
  }

  img {
    display: none;
    /* 隐藏原背景图 */
  }
}

/* 樱花飘落效果 */
.sakura-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 10;
  overflow: hidden;
}

.sakura {
  position: absolute;
  width: 20px;
  height: 20px;
  background: url('/src/assets/anime/sakura.png') no-repeat center/cover;
  top: -20px;
  animation: falling linear infinite;
  opacity: 0.7;
}

.floating-elements {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 5;
}

.floating-element {
  position: absolute;
  width: 30px;
  height: 30px;
  background-size: contain;
  background-repeat: no-repeat;
  opacity: 0.6;
  filter: drop-shadow(0 0 5px rgba(255, 255, 255, 0.6));

  &.heart {
    background-image: url('/src/assets/anime/images/heart.png');
    animation:
      float 6s ease-in-out infinite,
      pulse 3s ease-in-out infinite;
  }

  &.star {
    background-image: url('/src/assets/anime/images/star.png');
    animation:
      float 7s ease-in-out infinite 1s,
      twinkle 4s ease-in-out infinite;
  }

  &.cloud {
    background-image: url('/src/assets/anime/images/cloud.png');
    animation:
      float 5s ease-in-out infinite 0.5s,
      sway 8s ease-in-out infinite;
  }
}

/* 遮罩层 */
.kawaii-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    to right,
    rgba(255, 246, 249, 0.9) 30%,
    rgba(255, 246, 249, 0.7) 60%,
    rgba(255, 246, 249, 0.4) 100%
  );
  z-index: 1;
}

/* 动画效果 */
@keyframes falling {
  0% {
    transform: translateY(0) rotate(0deg);
    opacity: 0.7;
  }

  100% {
    transform: translateY(100vh) rotate(360deg);
    opacity: 0;
  }
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-15px);
  }
}

@keyframes twinkle {
  0%,
  100% {
    opacity: 0.6;
    transform: scale(1);
  }

  50% {
    opacity: 1;
    transform: scale(1.1);
  }
}

@keyframes pulse {
  0%,
  100% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.2);
  }
}

@keyframes sway {
  0%,
  100% {
    transform: translateX(0);
  }

  50% {
    transform: translateX(15px);
  }
}

@keyframes gradientShift {
  0% {
    opacity: 0.5;
  }

  50% {
    opacity: 0.8;
  }

  100% {
    opacity: 0.5;
  }
}

/* 在组件挂载时为每个樱花设置随机样式 */
@for $i from 1 through 12 {
  .sakura-#{$i} {
    left: random(100) * 1%;
    animation-duration: #{random(10) + 10}s;
    animation-delay: #{random(5)}s;
  }
}

.login-register {
  position: relative;
  flex: 1;
  padding: 30px 40px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  z-index: 2;
  max-width: 400px;
  margin-left: auto;
  box-shadow: 0 5px 15px rgba(255, 182, 193, 0.4);
  border: 2px solid rgba(255, 182, 193, 0.5);
}

.tab-panel {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  font-size: 18px;

  > div {
    padding: 0 20px;
    cursor: pointer;
    position: relative;
    color: #7c5479;
    transition: all 0.3s;

    &:hover {
      color: #fe4ea4;
    }

    &.active {
      color: #fe4ea4;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: -5px;
        left: 0;
        width: 100%;
        height: 3px;
        background: linear-gradient(to right, #fe4ea4, #ff9fcf);
        border-radius: 3px;
      }
    }
  }
}

:deep(.el-input) {
  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.6);
    border-radius: 25px;
    box-shadow: 0 2px 5px rgba(255, 182, 193, 0.2);
    transition: all 0.3s;

    &:hover,
    &.is-focus {
      box-shadow: 0 3px 10px rgba(255, 105, 180, 0.3) !important;
    }
  }

  .el-input__inner {
    height: 42px;
  }
}

.check-code-panel {
  display: flex;

  .check-code-input {
    flex: 1;
  }

  .check-code-btn {
    margin-left: 10px;
    border-radius: 25px;
    background: linear-gradient(to right, #c9a0dc, #b5a9d4);
    color: white;
    border: none;

    &:hover {
      background: linear-gradient(to right, #b794d1, #a89ccb);
    }
  }
}

.anime-button {
  background: linear-gradient(to right, #fe4ea4, #ff9fcf) !important;
  border: none !important;
  border-radius: 25px !important;
  transition: all 0.3s !important;
  font-size: 16px !important;
  letter-spacing: 1px !important;

  &:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 5px 15px rgba(254, 78, 164, 0.3) !important;
  }
}

.bottom-btn {
  margin-top: 20px;

  :deep(.el-form-item__content) {
    justify-content: center;

    .login-btn {
      width: 100%;
      height: 44px;
    }
  }
}

/* 底部协议 */
.agreement {
  text-align: center;
  margin-top: 20px;
  font-size: 12px;
  color: #999;

  .link {
    color: #fe4ea4;
    cursor: pointer;

    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
